package com.starry.module.system.core.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.starry.core.common.execption.ServiceException;
import com.starry.core.security.context.SecurityInfoContext;
import com.starry.module.system.api.member.domain.qo.MemberUserUpdateByLogin;
import com.starry.module.system.api.member.domain.vo.MemberUserLoginInfo;
import com.starry.module.system.core.member.entity.MemberUser;
import com.starry.module.system.core.member.mapper.MemberUserMapper;
import com.starry.module.system.core.member.service.AppMemberUserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * App会员用户-服务实现
 *
 * @author xiaoke
 */
@Service("appMemberUserService")
public class AppMemberUserServiceImpl implements AppMemberUserService {

    private final MemberUserMapper memberUserMapper;
    private final PasswordEncoder passwordEncoder;

    public AppMemberUserServiceImpl(MemberUserMapper memberUserMapper, PasswordEncoder passwordEncoder) {
        this.memberUserMapper = memberUserMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public MemberUserLoginInfo getByLoginInfo() {
        Long userId = SecurityInfoContext.getUserId();
        if (userId == null) {
            throw new ServiceException("会员未登录");
        }
        MemberUser memberUser = memberUserMapper.selectById(userId);
        if (memberUser == null) {
            throw new ServiceException("会员不存在");
        }
        return BeanUtil.toBean(memberUser, MemberUserLoginInfo.class);
    }

    @Override
    public void updateByLoginInfo(MemberUserUpdateByLogin memberUserLoginInfo) {
        Long userId = SecurityInfoContext.getUserId();
        if (userId == null) {
            throw new ServiceException("会员未登录");
        }
        MemberUser memberUser = memberUserMapper.selectById(userId);
        if (memberUser.getInitial()) {
            if (ObjectUtil.isAllNotEmpty(memberUserLoginInfo.getUsername())) {
                throw new ServiceException("会员已初始化，不允许修改用户名");
            }
        }
        BeanUtil.copyProperties(memberUserLoginInfo, memberUser);
        if (ObjectUtil.isAllNotEmpty(memberUserLoginInfo.getPassword())) {
            memberUser.setPassword(passwordEncoder.encode(memberUserLoginInfo.getPassword()));
        }
        memberUser.setInitial(true);
        memberUserMapper.updateById(memberUser);
    }
}
